package com.gfxy.modules.items.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gfxy.modules.common.entity.MemberList;
import com.gfxy.modules.common.entity.MemberSimpleList;
import com.gfxy.modules.common.service.IMemberListService;
import com.gfxy.modules.excel.TemplateUtil;
import com.gfxy.modules.items.entity.Bzsc;
import com.gfxy.modules.items.service.DictTranslater;
import com.gfxy.modules.items.vo.BzscMemberPage;
import com.gfxy.modules.items.vo.LxspyMemberPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.gfxy.modules.items.entity.Lxspy;
import com.gfxy.modules.items.vo.LxspyPage;
import com.gfxy.modules.items.service.ILxspyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 留学生培养
 * @Author: jeecg-boot
 * @Date:   2023-12-26
 * @Version: V1.0
 */
@Api(tags="留学生培养")
@RestController
@RequestMapping("/items/lxspy")
@Slf4j
public class LxspyController {
	@Autowired
	private ILxspyService lxspyService;
	 @Autowired
	 private IMemberListService memberListService;

	 @Autowired
	 private DictTranslater dictTranslater;

	 @Autowired
	 private TemplateUtil templateUtil;
	/**
	 * 分页列表查询
	 *
	 * @param date
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "留学生培养-分页列表查询")
	@ApiOperation(value="留学生培养-分页列表查询", notes="留学生培养-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(@RequestParam(name="date")  String date,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		IPage<LxspyMemberPage> pagePage = lxspyService.selectListPage(date, pageNo, pageSize);
		return Result.OK(pagePage);
	}
	
	/**
	 *   添加
	 *
	 * @param lxspyPage
	 * @return
	 */
	@AutoLog(value = "留学生培养-添加")
	@ApiOperation(value="留学生培养-添加", notes="留学生培养-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody LxspyPage lxspyPage) {
		Lxspy lxspy = new Lxspy();
		BeanUtils.copyProperties(lxspyPage, lxspy);
		lxspyService.saveMain(lxspy,lxspyPage.getMemberListList() );
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param lxspyPage
	 * @return
	 */
	@AutoLog(value = "留学生培养-编辑")
	@ApiOperation(value="留学生培养-编辑", notes="留学生培养-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody LxspyPage lxspyPage) {
		Lxspy lxspy = new Lxspy();
		BeanUtils.copyProperties(lxspyPage, lxspy);
		Lxspy lxspyEntity = lxspyService.getById(lxspy.getId());
		if(lxspyEntity==null) {
			return Result.error("未找到对应数据");
		}
		lxspyService.updateMain(lxspy, lxspyPage.getMemberListList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "留学生培养-通过id删除")
	@ApiOperation(value="留学生培养-通过id删除", notes="留学生培养-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		lxspyService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "留学生培养-批量删除")
	@ApiOperation(value="留学生培养-批量删除", notes="留学生培养-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.lxspyService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "留学生培养-通过id查询")
	@ApiOperation(value="留学生培养-通过id查询", notes="留学生培养-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Lxspy lxspy = lxspyService.getById(id);
		if(lxspy==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(lxspy);

	}
	 @AutoLog(value = "成员列表通过主表ID查询")
	 @ApiOperation(value="成员列表主表ID查询", notes="成员列表-通主表ID查询")
	 @GetMapping(value = "/queryMemberListByMainId")
	 public Result<?> queryMemberListListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<MemberList> memberListList = memberListService.selectByItemId(id);
		 return Result.OK(memberListList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param lxspy
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Lxspy lxspy) throws NoSuchFieldException {
      // Step.1 组装查询条件查询数据
		String date = lxspy.getDate();
		List<LxspyMemberPage> lxspyMemberPages = this.lxspyService.getMemberPageListByYear(date);
		List<String> title = new ArrayList<>();
		title.add("时间");
		title.add("类型");
		title.add("上课形式");
		title.add("人数");
		title.add("名称");
		title.add("成员");

		List<List<String>> contents = new ArrayList<>();
		for (LxspyMemberPage lxspyMemberPage : lxspyMemberPages) {
			List<String> content = new ArrayList<>();
			content.add(lxspyMemberPage.getDate());
			content.add(dictTranslater.getDictValue(LxspyMemberPage.class, "type", String.valueOf(lxspyMemberPage.getType())));
			content.add(dictTranslater.getDictValue(LxspyMemberPage.class, "kind", String.valueOf(lxspyMemberPage.getKind())));
			content.add(String.valueOf(lxspyMemberPage.getStudentNumber()));
			content.add(lxspyMemberPage.getProjectName());

			List<MemberSimpleList> list = lxspyMemberPage.getMemberListList();
			StringBuffer names = new StringBuffer();
			for (MemberSimpleList memberSimpleList : list) {
				names.append(memberSimpleList.getUserName()).append("、");
			}
			content.add(names.toString());


			contents.add(content);
		}

		ModelAndView mv = new ModelAndView(new TeachingExcelView());
		mv.addObject(TeachingExcelView.FILE_NAME, "留学生培育-"+date);
		mv.addObject(TeachingExcelView.TITLE, title);
		mv.addObject(TeachingExcelView.CONTENT, contents);
		return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
			  return Result.OK(this.lxspyService.importExcel(file));
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }
	 @AutoLog(value = "技能大赛-获取总分")
	 @ApiOperation(value="技能大赛-获取总分", notes="技能大赛-获取总分")
	 @GetMapping(value = "/getTotalScore")
	 public Result<?> getTotalScore(@RequestParam(name="type", defaultValue="0")  Integer type,
									@RequestParam(name="kind", defaultValue="0")  Integer kind,
									@RequestParam(name="studentNumber") Integer studentNumber,
									HttpServletRequest req) {

		 Lxspy lxspy = new Lxspy();
		 lxspy.setType(type);
		 lxspy.setKind(kind);
		 lxspy.setStudentNumber(studentNumber);

		 Double result = this.lxspyService.getTotalScore(lxspy);
		 return Result.OK(result);
	 }


	 @GetMapping(value = "/handleExportXlsTemplate")
	 public Result<?> download(HttpServletRequest request, HttpServletResponse response)  {
		 try {
			 templateUtil.template(response,TemplateUtil.LXSPY);
		 } catch (IOException e) {
			 e.printStackTrace();
			 return  Result.error("下载失败");
		 }
		 return  null;
	 }
}
